import { DictData } from "../types";
import mitt from "mitt";
let metaDict:{ cached: boolean, fetching: boolean, data: any[] } = {cached:false, fetching:false, data:[]};

const emitter = mitt();
const event: Record<string, string> = {
    DictReady: "dictReady",
}

export function addMetaDict(data: DictData): Promise<any> {
    const url = '/meta/dict/add';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, data)
            .then((response: any) => {
                if(!metaDict){
                    metaDict = {cached:false, fetching:false, data:[]};
                }
                metaDict.cached = false;
                resolve(response);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
}

export function getMetaDictByPid(pid: string|number): Promise<any> {
    return new Promise((resolve,reject) => {
        getAllMetaDict().then((data: any[]) => {
            resolve(data.filter((item: any) => item.pid == pid));
        }).catch(() => {
            reject([]);
        });
    });
}
export function getMetaDictById(id: string|number): Promise<any> {
    return new Promise((resolve,reject) => {
        getAllMetaDict().then((data: any[]) => {
            resolve(data.find((item: any) => item.id == id)||{});
        }).catch(() => {
            reject({});
        });
    });
}
export function getMetaDictByValueAndPid(pid: string|number,value:string): Promise<any> {
    return new Promise((resolve,reject) => {
        getAllMetaDict().then((data: any[]) => {
            resolve(data.find((item: any) => item.pid == pid && item.value == value));
        }).catch(() => {
            reject({});
        });
    });
}
export function getAllMetaDict(): Promise<any> {
    if(!metaDict){
        metaDict = { cached: false, fetching: false, data: [] };
    }
    if (metaDict.cached) {
        return new Promise((resolve) => {
            resolve(metaDict.data);
        });
    }
    if (metaDict.fetching) {
        return new Promise((resolve) => {
            emitter.on(event.DictReady, () => {
                resolve(metaDict.data);
            })
            if (metaDict.cached) {
                resolve(metaDict.data);
            }
        });
    }
    metaDict.fetching = true;
    const url = '/meta/dict/query';
    return new Promise((resolve, reject) => {
        window.$theia.http
            .post(url, {})
            .then((response: any) => {
                metaDict.cached = true;
                metaDict.fetching = false;
                metaDict.data = response;
                emitter.emit(event.DictReady);
                resolve(response);
            })
            .catch((err: any) => {
                metaDict.fetching = false;
                reject(err);
            });
    });
}